package xyz.scootaloo.kami.server.model.dao

import org.ktorm.dsl.eq
import org.ktorm.entity.*
import xyz.scootaloo.kami.server.model.SysRule
import xyz.scootaloo.kami.server.model.rules
import xyz.scootaloo.kami.server.standard.currentTimeMillis
import xyz.scootaloo.kami.server.verticle.database

/**
 * @author flutterdash@qq.com
 * @since 2022/2/8 11:06
 */
object RuleDAO {

    fun list(): List<SysRule> {
        return database.rules.toList()
    }

    fun store(path: String, accessRule: ByteArray) {
        val record = database.rules.find { it.path eq path }
        if (record != null) {
            record.updated = currentTimeMillis()
            record.accessRule = accessRule
            record.flushChanges()
        } else {
            database.rules.add(SysRule.create(path, accessRule))
        }
    }

    fun delete(path: String) {
        database.rules.find { it.path eq path }?.delete()
    }
}